package com.apiz.gateway;

import com.apiz.common.model.entity.InterfaceInfo;
import com.apiz.common.model.entity.User;
import com.apiz.common.service.InnerInterfaceInfoService;
import com.apiz.common.service.InnerUserInterfaceInfoService;
import com.apiz.common.service.InnerUserService;
import com.apiz.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    public static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");

    @DubboReference
    InnerInterfaceInfoService interfaceInfoService;

    @DubboReference
    InnerUserInterfaceInfoService userInterfaceInfoService;

    @DubboReference
    InnerUserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 请求日志
        ServerHttpRequest request = exchange.getRequest();
        log.info("请求唯一标识"+request.getId());
        log.info("请求路径"+request.getPath().value());
        log.info("请求方法"+request.getMethod());
        log.info("请求参数"+request.getQueryParams());
        log.info("请求来源地址"+request.getRemoteAddress().getHostString());
        log.info("请求来源地址"+request.getRemoteAddress());

        String sourceAddress = request.getRemoteAddress().getHostString();
        String path = request.getPath().value();
        String method = request.getMethod().name();

        ServerHttpResponse response = exchange.getResponse();
        // 2. 访问控制 - 黑白名单
//        if (!IP_WHITE_LIST.contains(sourceAddress)){
//           return handleNoAuth(response);
//        }
        // 3. 用户鉴权（判断 ak、sk 是否合法）

        HttpHeaders headers = request.getHeaders();

        String accessKey = headers.getFirst("accessKey");
        String nonce =  headers.getFirst("nonce");
        String body =  headers.getFirst("body");
        String timeStamp = headers.getFirst("timeStamp");
        String sign =  headers.getFirst("sign");


        //todo accessKey 去数据库查 是否已分配给用户
        User user = userService.getInvokeUser(accessKey);
        if (user == null){
            return handleNoAuth(response);
        }

        if (Long.parseLong(nonce) > 10000){
            return handleNoAuth(response);
        }
        //todo 和当前时间不能超过5分钟
        Long currentTime = System.currentTimeMillis()/1000;

        final Long FIVE_MINUTES = 60*5L;
        if (currentTime - Long.parseLong(timeStamp) > FIVE_MINUTES){
            return handleNoAuth(response);
        }

        // 实际情况中是从数据库中查出 secretKey
        String serverSign = SignUtil.getSign(body,user.getSecretKey());
        if (!sign.equals(serverSign)){
            throw new RuntimeException("参数错误");
        }

        // todo 请求的模拟接口是否存在，以及请求方法是否匹配
        InterfaceInfo interfaceInfo = interfaceInfoService.getInterfaceInfo(path,method);

        if (interfaceInfo == null){
            throw new RuntimeException("接口不匹配");
        }

        // todo 查看 是否有調用資格 1.是否分配給用戶接口 是否有調用次數
        boolean judgeInvoke = userInterfaceInfoService.invokeCondition(interfaceInfo.getId(),user.getId());

        if (!judgeInvoke){
            throw new RuntimeException("没有调用接口的资格哦");
        }

        // 5. 请求转发，调用模拟接口 + 响应日志
//        Mono<Void> filter = chain.filter(exchange);
//
//        //        Mono<Void> filter = chain.filter(exchange);
//        //        return filter;
//
//        if (response.getStatusCode() != HttpStatus.OK){
//            handleError(response);
//        }
        return handleResponse(exchange,chain,interfaceInfo.getId(),user.getId());
    }

    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,Long interfaceId,Long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            // 拼接字符串
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {

                                        // todo 7. 调用成功，接口调用次数 + 1 invokeCount
                                        boolean result = userInterfaceInfoService.invokeCount(interfaceId,userId);
                                        if (!result){
                                            throw new RuntimeException("接口调用异常");
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        String data = new String(content, StandardCharsets.UTF_8); //data
                                        sb2.append(data);
                                        // 打印日志
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    }));
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    private Mono<Void> handleNoAuth(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }
    private Mono<Void> handleError(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }
}

